package cn.lg.soar.database.handler.type.base;

import cn.lg.soar.common.util.jackson.JacksonUtil;
import cn.lg.soar.common.util.reflect.GenericTypeUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;

/**
 * Set<T> 类型处理器
 * @author luguoxiang
 * @date 2022-05-20
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public abstract class SetTypeHandler<T> extends AbstractJsonTypeHandler<Set<T>> {

    protected CollectionType collectionType;

    private final static ObjectMapper OBJECT_MAPPER = JacksonUtil.OBJECT_MAPPER;

    public SetTypeHandler() {
        super(Object.class);
        Type genericType = GenericTypeUtils.getSuperclassGenericType(this.getClass());
        collectionType = OBJECT_MAPPER
                .getTypeFactory()
                .constructCollectionType(HashSet.class, (Class<T>) genericType);
    }

    public SetTypeHandler(Class<T> type) {
        super(type);
        collectionType = OBJECT_MAPPER
                .getTypeFactory()
                .constructCollectionType(HashSet.class, type);
    }

    @Override
    public Set<T> parse(String json) {
        try {
            return OBJECT_MAPPER.readValue(json, collectionType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toJson(Set<T> obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
